package com.xgkj.diyiketang.activity;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.provider.MediaStore;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.SurfaceView;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.JavascriptInterface;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.VideoView;

import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.WXAPIFactory;
import com.xgkj.diyiketang.ProtocolConst;
import com.xgkj.diyiketang.data.EatShowUserInfo;
import com.xgkj.diyiketang.http.engine.ShowToastTaskEventListener;
import com.xgkj.diyiketang.task.GetUserDetailTask;
import com.xgkj.diyiketang.util.EatShowSetting;
import com.xgkj.diyiketang.util.GetImagePathUtil;
import com.xgkj.diyiketang.util.PalLog;
import com.xgkj.diyiketang.util.ShareUtil;
import com.xgkj.diyiketang.util.ViewUtil;
import com.xgkj.diyiketang.util.WeiXinPay;
import com.xgkj.diyiketang.R;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;

/**
 *
 */
public class WebViewActivity extends BaseActivity implements View.OnClickListener{

    private static final String TAG =WebViewActivity.class.getSimpleName() ;
    private WebView mWebView;
    private static String mUrl;
    final IWXAPI msgApi = WXAPIFactory.createWXAPI(this, null);
    private Context mContext;
    private PopupWindow popWindow;
    private static final int CAMERA_REQUEST = 2;
    private static final int CHOOSE_REQUEST = 11;
    private File mFile;
    private static final String CAMERA_FILE = "diyiketang/img";
    private TextView backText;
    private ViewGroup mVideoViewContainer;
    private LinearLayout pop_shade;
    private Handler mHandler = new Handler();
    private String school="";

    private int isLive = -1;

    private int mIsVip ;
    private int mVipCode;

    @Override
    protected void onCreate(Bundle savedInstanceStat) {
        super.onCreate(savedInstanceStat);
        setContentView(R.layout.webview_layout);
        mContext = this;
        school = getEatShowApp().getmUserInfo().getSchoolName();
        if(ViewUtil.isNull(school)){
            school = "";
        }

        PalLog.e("所在学校",school);
        File folder = EatShowSetting.getInstance(mContext).getDataFolder(CAMERA_FILE);
        String fileName = "IMG"+ System.currentTimeMillis()+".jpeg";
        mFile = new File(folder,fileName);
        initPopWindow();
        msgApi.registerApp(ProtocolConst.APP_ID);
        pop_shade = (LinearLayout) findViewById(R.id.popwindow_shade);
        mWebView = (WebView)findViewById(R.id.webview);
//        final ProgressBar progressbar = (ProgressBar)findViewById(R.id.progressBar);
//        progressbar.setVisibility(View.GONE);
        mWebView.getSettings().setJavaScriptCanOpenWindowsAutomatically(false);
        mWebView.getSettings().setSupportMultipleWindows(false);
       /* mWebView.setWebChromeClient(new WebChromeClient(){
            public void onProgressChanged(WebView view, int newProgress) {

//                progressbar.setProgress(newProgress);
            }

			@Override
			public boolean onJsAlert(WebView view, String url, String message,
					JsResult result) {
				// TODO Auto-generated method stub
				return super.onJsAlert(view, url, message, result);
			}


            
        });*/
        MyWebChromeClient client = new MyWebChromeClient();
        mWebView.setWebChromeClient(client);
        mVideoViewContainer = (ViewGroup) findViewById(R.id.fullscreen_layout);
        /*client.init(mWebView, mWebView, mVideoViewContainer,
                new Callback() {

                    @Override
                    public void enterFullscreenVideo() {
                        WindowManager.LayoutParams attrs = getWindow().getAttributes();
                        attrs.flags |= WindowManager.LayoutParams.FLAG_FULLSCREEN;
                        attrs.flags |= WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON;
                        getWindow().setAttributes(attrs);
                        if (android.os.Build.VERSION.SDK_INT >= 14) {
                            // noinspection all
                            getWindow().getDecorView().setSystemUiVisibility(
                                    View.SYSTEM_UI_FLAG_LOW_PROFILE);
                        }

                        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
                    }

                    @Override
                    public void exitFullscreenVideo() {
                        WindowManager.LayoutParams attrs = getWindow().getAttributes();
                        attrs.flags &= ~WindowManager.LayoutParams.FLAG_FULLSCREEN;
                        attrs.flags &= ~WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON;
                        getWindow().setAttributes(attrs);
                        if (android.os.Build.VERSION.SDK_INT >= 14) {
                            // noinspection all
                            getWindow().getDecorView().setSystemUiVisibility(
                                    View.SYSTEM_UI_FLAG_VISIBLE);
                        }

                        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
                    }

                });*/
        mWebView.setWebViewClient(new WebViewClient() {
            public boolean shouldOverrideUrlLoading(WebView view, String url){
                view.loadUrl(url);
                return false;
            }
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
//                progressbar.setVisibility(View.VISIBLE);
            }
            public void onPageFinished(WebView view, String url) {
//                progressbar.setVisibility(View.GONE);
//                refreshState();
            }
        });
        mWebView.getSettings().setJavaScriptEnabled(true);
        mWebView.addJavascriptInterface(new goShareActivity(), "goShare");
        if(mUrl!=null){
            mWebView.loadUrl(mUrl);
        }

        backText = (TextView) findViewById(R.id.back);
        backText.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                WebViewActivity.this.finish();
            }
        });

//        findViewById(R.id.refresh).setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                mWebView.reload();
//            }
//        });
//
//        findViewById(R.id.backward).setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                mWebView.goBack();
//                refreshState();
//            }
//        });
//
//        findViewById(R.id.forward).setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                mWebView.goForward();
//                refreshState();
//            }
//        });

//        refreshState();
    }

    private void refreshState() {
        PalLog.d(TAG,"refreshState");
        if(mWebView.canGoBack()){
            PalLog.d(TAG,"canGoBack");
//            findViewById(R.id.backward).setEnabled(true);
        } else {
//            findViewById(R.id.backward).setEnabled(false);
        }

        if(mWebView.canGoForward()){
            PalLog.d(TAG,"canGoForward");
//            findViewById(R.id.forward).setEnabled(true);
        } else {
//            findViewById(R.id.forward).setEnabled(false);
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mWebView.destroy();
    }

    public static Intent getIntent(Context context, String url) {
        Intent intent = new Intent(context, WebViewActivity.class);
        Bundle bundle = new Bundle();
        intent.putExtras(bundle);
        if(url!=null){
            if(url.startsWith("http") || url.startsWith("https")) {
                mUrl = url;
            }else{
                mUrl = "http://"+url;
            }
        }
        return intent;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.takephoto:
                popWindow.dismiss();
                Intent camera_intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                camera_intent
                        .putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(mFile));
                startActivityForResult(camera_intent, CAMERA_REQUEST);
                break;
            case R.id.choosephoto:
                popWindow.dismiss();
//                Intent intent = new Intent(mContext, PhoneMainActivity.class);
//                startActivityForResult(intent,300);
                Intent choose_intent = new Intent();
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
                    choose_intent.setAction(Intent.ACTION_OPEN_DOCUMENT);
                } else {
                    choose_intent.setAction(Intent.ACTION_GET_CONTENT);
                }
                choose_intent.setType("image/*");
                startActivityForResult(choose_intent, CHOOSE_REQUEST);
                break;
            case R.id.cancle:
                popWindow.dismiss();
                if (mUploadMessage != null){
                    mUploadMessage.onReceiveValue(null);
                    mUploadMessage = null;
                }
                break;
        }
    }

    class goShareActivity{
    	@JavascriptInterface
		public void go() {
			PalLog.e(TAG,"####################调用wap页面分享######################");
            new WeiXinPay(msgApi, WebViewActivity.this, "135999993333", "h5充值", "1");
		}


        @JavascriptInterface
        public void showShare() {
            mHandler.post(new Runnable() {
                @Override
                public void run() {
                    pop_shade.setVisibility(View.VISIBLE);
                    String share_title = "第一课堂邀请您的加入~~~~";
                    String myuserId = null;
                    if (getEatShowApp().getmUserInfo() != null){
                        myuserId =  getEatShowApp().getmUserInfo().getUserId();
                    }
                    String share_url = "http://app.sjmingze.com/register/register.html?commId="+myuserId+ "&schoolName=" + school;
                    PalLog.e("share_url",share_url);
                    ShareUtil.getInstance(mContext).show(share_title, share_url, new PopupWindow.OnDismissListener() {
                                @Override
                                public void onDismiss() {
                                    pop_shade.setVisibility(View.GONE);
                                }
                            },
                            mWebView);
                }
            });
        }
    }

    /*直播的 判断方法请求*/
    public void getUserInfoIsLive() {
        GetUserDetailTask task = new GetUserDetailTask();
        task.addListener(new ForgetUserInfoTaskEventListener(mContext));
        isLive = getEatShowApp().getTaskManager().addTask(task);

    }

    class ForgetUserInfoTaskEventListener extends ShowToastTaskEventListener {
        public ForgetUserInfoTaskEventListener (Context context) {
            super(context);
        }

        @Override
        public void handleTaskCompleted(int taskId, int result, Object data) {
            super.handleTaskCompleted(taskId, result, data);
            if(taskId == isLive) {
                isLive = -1;

                Log.e("taskId:+result:+data::","taskId"+taskId+"++"+result+":::"+data.toString());
                // EatShowApp data1 = (EatShowApp) data;
                EatShowUserInfo data1 = (EatShowUserInfo) data;
                //canStartLive = data1.getCanStartLive();
                 mIsVip = data1.isVip();

                if(getEatShowApp().getmUserInfo()!=null){
                   // getEatShowApp().getmUserInfo().setCanStartLive(canStartLive);

                }

            }
        }

        @Override
        public void handleTaskError(int taskId, int errorCode, String errorMsg) {
            super.handleTaskError(taskId, errorCode, errorMsg);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        PalLog.e(TAG,"33333");
        if (null == mUploadMessage) return;
        PalLog.e(TAG,"444444");
        Uri result = null;

        if (requestCode == CHOOSE_REQUEST) {
            PalLog.e(TAG,"5555555");

            if (data != null){
                result = data.getData();
            }

            if (result != null) {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
                    String local_url = GetImagePathUtil.getPath(mContext, result);
                    PalLog.e(TAG,local_url+"图片位置");
//                    result = Uri.fromFile(new File(local_url));
                    Bitmap bitmap = createNoSizeBitmap(local_url);
                    BufferedOutputStream out = null;
//                    if (!mFile.exists()){
//                        mFile.mkdirs();
//                    }

                    try {
                        out = new BufferedOutputStream(new FileOutputStream(mFile));
                    } catch (FileNotFoundException e) {
                        e.printStackTrace();
                    }
                    if (bitmap != null && out != null) {
                        boolean isSuccess = bitmap.compress(Bitmap.CompressFormat.JPEG,
                                100, out);
                        result = Uri.fromFile(mFile);
                    }
                }
            }
        }else if (requestCode == CAMERA_REQUEST){

            if (mFile != null && mFile.exists()){
                String local_url = mFile.getAbsolutePath();
                Bitmap bitmap = createNoSizeBitmap(local_url);
                BufferedOutputStream out = null;
//                    if (!mFile.exists()){
//                        mFile.mkdirs();
//                    }

                try {
                    out = new BufferedOutputStream(new FileOutputStream(mFile));
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                }
                if (bitmap != null && out != null) {
                    boolean isSuccess = bitmap.compress(Bitmap.CompressFormat.JPEG,
                            100, out);
                    result = Uri.fromFile(mFile);
                }
                PalLog.e(TAG,"666666");
            }
        }
        PalLog.e(TAG,result != null ? result.toString() :null);
        mUploadMessage.onReceiveValue(result);
        mUploadMessage = null;
    }

    private Bitmap createNoSizeBitmap(String fileDescriptor) {
        Bitmap bitmap = null;
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(fileDescriptor,options);
//        BitmapFactory.decodeFileDescriptor(fileDescriptor, null, options);
        int i = 1;
        while (true) {
            if ((options.outWidth/i <= 360)
                    && (options.outHeight/i <= 360)) {
                options.inSampleSize = i;
                options.inJustDecodeBounds = false;
                bitmap = BitmapFactory.decodeFile(fileDescriptor, options);
                break;
            }
            i += 1;
        }
        return bitmap;
    }


    private void initPopWindow() {
        View view = LayoutInflater.from(mContext).inflate(R.layout.popwindow,
                null);
        ((Button) view.findViewById(R.id.takephoto)).setOnClickListener(this);
        ((Button) view.findViewById(R.id.choosephoto)).setOnClickListener(this);
        ((Button) view.findViewById(R.id.cancle)).setOnClickListener(this);
        popWindow = new PopupWindow(view, LinearLayout.LayoutParams.MATCH_PARENT,
                LinearLayout.LayoutParams.WRAP_CONTENT);
//        popWindow.setBackgroundDrawable(new ColorDrawable());
        popWindow.setFocusable(true);
        popWindow.setOutsideTouchable(false);
//        popWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
//            @Override
//            public void onDismiss() {
//                if (mUploadMessage != null){
//                    PalLog.e(TAG,"777777777");
//                    mUploadMessage.onReceiveValue(null);
//                    mUploadMessage = null;
//                }
//            }
//        });
    }


    private ValueCallback<Uri> mUploadMessage;

    public interface Callback {
        void enterFullscreenVideo();

        void exitFullscreenVideo();
    }

    class MyWebChromeClient extends WebChromeClient implements MediaPlayer.OnPreparedListener,MediaPlayer.OnCompletionListener,MediaPlayer.OnErrorListener{
        boolean mIsVideoFullscreen = false;
        FrameLayout mVideoViewFrameLayout;
        CustomViewCallback mVideoViewCallback;

        Callback mOutCallback;
        private View mNonFullscreenVideoLayout;
        private ViewGroup mFullscreenVideoLayout;

        @Override
        public void onCompletion(MediaPlayer mp) {
            onHideCustomView();
        }

        @Override
        public boolean onError(MediaPlayer mp, int what, int extra) {
            return false;
        }

        @Override
        public void onPrepared(MediaPlayer mp) {

        }


        class JavaScriptInterface {

            WebChromeClient mWebChromeClient;

            public JavaScriptInterface(WebChromeClient webChromeClient) {
                mWebChromeClient = webChromeClient;
            }

            @android.webkit.JavascriptInterface
            @SuppressWarnings("unused")
            public void notifyVideoEnd() {
                new Handler(Looper.getMainLooper()).post(new Runnable() {
                    @Override
                    public void run() {
                        if (mWebChromeClient != null) {
                            mWebChromeClient.onHideCustomView();
                        }
                    }
                });
            }
        }

        public void init(WebView webview, View nonFullscreenVideoLayout,
                         ViewGroup fullScreenVideoLayout,
                         Callback callback) {
            mWebView = webview;
            mNonFullscreenVideoLayout = nonFullscreenVideoLayout;
            mFullscreenVideoLayout = fullScreenVideoLayout;
            mOutCallback = callback;

            webview.addJavascriptInterface(new JavaScriptInterface(this),
                    "_VideoEnabledWebView");
        }



        // For Android 3.0+
        public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType) {
//            if (mUploadMessage != null) return;
            PalLog.e(TAG,"11111111");
            mUploadMessage = uploadMsg;
//            selectImage();
            popWindow.showAtLocation(backText, Gravity.BOTTOM,0,0);
            PalLog.e(TAG,"2222222");
        }

        // For Android < 3.0
        public void openFileChooser(ValueCallback<Uri> uploadMsg) {
            openFileChooser( uploadMsg, "" );
        }

        // For Android  > 4.1.1
        public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType, String capture) {
            openFileChooser(uploadMsg, acceptType);
        }


        @Override
        public void onShowCustomView(View view, CustomViewCallback callback) {

            if (view instanceof FrameLayout) {
                // A video wants to be shown
                FrameLayout frameLayout = (FrameLayout) view;
                View focusedChild = frameLayout.getFocusedChild();

                // Save video related variables
                mIsVideoFullscreen = true;
                mVideoViewFrameLayout = frameLayout;
                mVideoViewCallback = callback;

                // Hide the non-video view, add the video view, and show it
                mNonFullscreenVideoLayout.setVisibility(View.INVISIBLE);
                mFullscreenVideoLayout.addView(mVideoViewFrameLayout, new ViewGroup.LayoutParams(
                        ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
                mFullscreenVideoLayout.setVisibility(View.VISIBLE);

                if (focusedChild instanceof android.widget.VideoView) {
                    // android.widget.VideoView (typically API level <11)
                    VideoView videoView = (VideoView) focusedChild;

                    // Handle all the required events
                    videoView.setOnPreparedListener(this);
                    videoView.setOnCompletionListener(this);
                    videoView.setOnErrorListener(this);
                } else {
                    // Other classes, including:
                    // - android.webkit.HTML5VideoFullScreen$VideoSurfaceView,
                    // which inherits from android.view.SurfaceView (typically
                    // API level 11-18)
                    // - android.webkit.HTML5VideoFullScreen$VideoTextureView,
                    // which inherits from android.view.TextureView (typically
                    // API level 11-18)
                    // -
                    // com.android.org.chromium.content.browser.ContentVideoView$VideoSurfaceView,
                    // which inherits from android.view.SurfaceView (typically
                    // API level 19+)

                    // Handle HTML5 video ended event only if the class is a
                    // SurfaceView
                    // Test case: TextureView of Sony Xperia T API level 16
                    // doesn't work fullscreen when loading the javascript below
                    if (mWebView != null && mWebView.getSettings().getJavaScriptEnabled()
                            && focusedChild instanceof SurfaceView) {
                        // Run javascript code that detects the video end and
                        // notifies the Javascript interface
                        String js = "javascript:";
                        js += "var _ytrp_html5_video_last;";
                        js += "var _ytrp_html5_video = document.getElementsByTagName('video')[0];";
                        js += "if (_ytrp_html5_video != undefined && _ytrp_html5_video != _ytrp_html5_video_last) {";
                        {
                            js += "_ytrp_html5_video_last = _ytrp_html5_video;";
                            js += "function _ytrp_html5_video_ended() {";
                            {
                                js += "_VideoEnabledWebView.notifyVideoEnd();";
                            }
                            js += "}";
                            js += "_ytrp_html5_video.addEventListener('ended', _ytrp_html5_video_ended);";
                        }
                        js += "}";

                        injectJS(mWebView, js);
                    }
                }

                // Notify full-screen change
                if (mOutCallback != null) {
                    mOutCallback.enterFullscreenVideo();
                }
            }

        }

        @Override
        public void onHideCustomView() {
            // This method should be manually called on video end in all cases
            // because it's not always called automatically.
            // This method must be manually called on back key press (from this
            // class' onBackPressed() method).

            if (mIsVideoFullscreen) {
                // Hide the video view, remove it, and show the non-video view
                mFullscreenVideoLayout.setVisibility(View.INVISIBLE);
                mFullscreenVideoLayout.removeView(mVideoViewFrameLayout);
                mNonFullscreenVideoLayout.setVisibility(View.VISIBLE);

                // Call back (only in API level <19, because in API level 19+ with
                // chromium webview it crashes)
                if (mVideoViewCallback != null
                        && !mVideoViewCallback.getClass().getName().contains(".chromium.")) {
                    mVideoViewCallback.onCustomViewHidden();
                }

                // Reset video related variables
                mIsVideoFullscreen = false;
                mVideoViewFrameLayout = null;
                mVideoViewCallback = null;

                // Notify full-screen change
                if (mOutCallback != null) {
                    mOutCallback.exitFullscreenVideo();
                }
            }
        }

        private void injectJS(WebView webview, String script) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
                webview.evaluateJavascript(script, null);
            } else {
                webview.loadUrl("javascript:" + script);
            }
        }


    }
}
